<template>
    <view>
        <form v-if="webConfig.open_comment === '1'">
            <view class="cu-form-group margin-top">
                <view class="title">*bug描述（或建议）</view>
                <input @input="Input" data-field="function" placeholder="功能名称，如“留言板”" />
            </view>
            <view class="cu-bar bg-white margin-top">
                <view class="action">bug截图</view>
                <view class="action">{{ imgList.length }}/9</view>
            </view>
            <view class="cu-form-group">
                <view class="grid col-4 grid-square flex-sub">
                    <view class="bg-img" @tap="ViewImage" :data-url="imgList[index]" v-for="(item, index) in imgList" :key="index">
                        <image :src="imgList[index]" mode="aspectFill"></image>

                        <view class="cu-tag bg-red" @tap.stop.prevent="DelImg" :data-index="index">
                            <text class="cuIcon-close"></text>
                        </view>
                    </view>
                    <view class="solids" @tap="ChooseImage" v-if="imgList.length < 9">
                        <text class="cuIcon-cameraadd"></text>
                    </view>
                </view>
            </view>
            <view class="cu-form-group align-start">
                <view class="title">*bug描述（或者建议）</view>
                <textarea maxlength="-1" @input="Input" data-field="description" placeholder="描述内容"></textarea>
            </view>
            <button
                class="cu-btn bg-blue shadow-red"
                data-type="pet"
                style="width: 579rpx; height: 64rpx; display: flex; box-sizing: border-box; left: 0rpx; top: 0rpx"
                @tap="Submit"
            >
                发布
            </button>
        </form>
        <view v-if="webConfig.open_comment !== '1'">功能开发中</view>
    </view>
</template>

<script>
// pages/publish/publish.js
const app = getApp();

const getData = (url, param) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: url,
            method: 'POST',
            data: param,
            header: {
                'Content-Type': 'application/json'
            },

            success(res) {
                resolve(res.data);
            },

            fail(err) {
                reject(err);
            }
        });
    });
}; //获取随机数

const charts = [
    '0',
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G',
    'H',
    'I',
    'J',
    'K',
    'L',
    'M',
    'N',
    'O',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'U',
    'V',
    'W',
    'X',
    'Y',
    'Z'
];

const random = function generateMixed(n) {
    var res = '';

    for (var i = 0; i < n; i++) {
        var id = Math.ceil(Math.random() * 35);
        res += charts[id];
    }

    return res;
};

export default {
    data() {
        return {
            Detail: {
                SafeCode: '',
                code: ''
            },
            //信息详情
            webConfig: {
                open_comment: ''
            },
            index: '',
            imgList: [],
            code: ''
        };
    }
    /**
     * 生命周期函数--监听页面加载
     */,
    onLoad: function (options) {
        var that = this;
        that.SafeCode = uni.getStorageSync('SafeCode'); //获取网站配置

        uni.request({
            url: app.globalData.ApiUrl + 'api/Wechat/webConfig',
            //这里填写你的接口路径
            header: {
                'Content-Type': 'application/json'
            },
            success: function (res) {
                that.setData({
                    webConfig: res.data
                });
            }
        }); //先确定SafeCode

        this.setData({
            'Detail.SafeCode': uni.getStorageSync('SafeCode')
        }); //随机码生成

        var code = random(32);
        this.setData({
            code: code,
            'Detail.code': code
        });
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {},
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {},
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {},
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {},
    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {},
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {},
    methods: {
        Input: function (e) {
            var field = 'Detail.' + e.currentTarget.dataset.field;
            var val = e.detail.value;
            this.Detail.e.currentTarget.dataset.field = val;
            console.log(this);
        },

        ChooseImage: function (e) {
            uni.chooseImage({
                count: 9,
                //默认9
                sizeType: ['original'],
                //可以指定是原图还是压缩图，默认二者都有
                sourceType: ['album', 'camera'],
                //从相册选择
                success: (res) => {
                    if (this.imgList.length != 0) {
                        this.setData({
                            imgList: this.imgList.concat(res.tempFilePaths)
                        });
                    } else {
                        this.setData({
                            imgList: res.tempFilePaths
                        });
                    }
                }
            });
        },

        ViewImage(e) {
            uni.previewImage({
                urls: this.imgList,
                current: e.currentTarget.dataset.url
            });
        },

        DelImg(e) {
            this.imgList.splice(e.currentTarget.dataset.index, 1);
            this.setData({
                imgList: this.imgList
            });
        },

        Submit: function (e) {
            var that = this;
            var allReady = true; //假设目前一切正常

            var msg = '出了点小问题'; //错误信息报告
            //使用循环上传

            for (var i = 0; i < that.imgList.length; i++) {
                uni.uploadFile({
                    url: app.globalData.ApiUrl + 'api/Wechat/UploadApi',
                    filePath: that.imgList[i],
                    name: 'img_file',
                    formData: {
                        code: that.code
                    },
                    success: function (res) {
                        if (res.data.result === 'success') {
                            console.log('上传成功' + i);
                        } else {
                            allReady = false;
                            console.log('上传失败');
                        }
                    },
                    fail: function (res) {
                        allReady = false;
                    }
                });
            }

            getData(app.globalData.ApiUrl + 'api/Wechat/SubmitBug', that.Detail).then(
                (res) => {
                    if (res.result !== 'success') {
                        msg = res.msg;
                        allReady = false;
                    }
                },
                (err) => {
                    allReady = false;
                }
            );

            if (allReady) {
                uni.showToast({
                    title: '反馈成功！',
                    icon: 'success',
                    duration: 1500
                });
                setTimeout(function () {
                    uni.navigateBack();
                }, 1500);
            } else {
                uni.showToast({
                    title: msg,
                    icon: 'error',
                    duration: 1500
                });
            }
        }
    }
};
</script>
<style>
@import './bug.css';
</style>
